#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <functional>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

#define BACKLOG 5
using namespace std;
using namespace Log_Module;

static const uint16_t gport = 8080;
using hander_t = function<string(string)>;

class Tcp_Server
{
private:
    int _listenfd;
    uint16_t _port;
    bool _isrunning;
    hander_t _handler;

public:
    Tcp_Server(hander_t handler, int port = gport)
        : _handler(handler), _port(port), _isrunning(false)
    {
    }
    void InitServer()
    {
        _listenfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listenfd < 0)
        {
            LOG(LogLevel::ERROR) << "socket error";
            Die(SCOKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket create success, sockfd is : " << _listenfd;

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(gport);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listenfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "bind error";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success,success is" << _listenfd;

        n = listen(_listenfd, BACKLOG);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "listen error";
            Die(Listen_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is : " << _listenfd;
    }

    void HandlerRequest(int sockfd) // TCP也是全双工通信的
    {
        LOG(LogLevel::INFO) << "accept a connection, sockfd is : " << sockfd;
        char inbuf[1024];
        while (true)
        {
            ssize_t n = recv(sockfd, inbuf, sizeof(inbuf), 0);
            if (n > 0)
            {
                LOG(LogLevel::INFO) << "recv data from client, data is : " << inbuf;
                inbuf[n] = 0;
                string result = _handler(inbuf);
                send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client close the connection";
                break;
            }
            else
            {
                break;
            }
        }
        close(sockfd); // fd泄漏问题，fd是随进程结束而释放的，所以在这里关闭fd
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 不能直接读取数据
            // 1. 获取新连接
            struct sockaddr_in peer;
            socklen_t peerlen = sizeof(peer); // 这个地方一定要注意，要不然，会有问题！
            LOG(LogLevel::DEBUG) << "accept ing ...";
            // 我们要获取client的信息：数据(sockfd)+client socket信息(accept || recvfrom)
            int sockfd = ::accept(_listenfd, (struct sockaddr*)(&peer), &peerlen);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error: " << strerror(errno);
                continue;
            }
            LOG(LogLevel::INFO) << "acccept success, sockfd is : " << sockfd;
            // 2. 处理请求
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "通过accept的输出型参数，获取到的client info: " << addr.Addr();
            
            // version-0
            // HandlerRequest(sockfd);

            //version-1: 多进程版本
            pid_t id = fork();
            if (id == 0)
            {
                // child
                // 问题1: 子进程继承父进程的文件描述符表。两张，父子各一张
                // 1. 关闭不需要的fd
                ::close(_listenfd);
                if(fork() > 0) exit(0); //子进程退出
                // 孙子进程 -> 孤儿进程 -> 1
                HandlerRequest(sockfd);
                exit(0);
            }
            ::close(sockfd);
            // 不会阻塞
            int rid = ::waitpid(id, nullptr, 0);
            if(rid < 0)
            {
                LOG(LogLevel::WARNING) << "waitpid error";
            }
            // version-2: 多线程版本
            // 主线程和新线程是如何看待：文件描述符表，共享一张文件描述符表！！
            // pthread_t tid;
            // ThreadData *data = new ThreadData;
            // data->sockfd = sockfd;
            // data->self = this;
            // pthread_create(&tid, nullptr, ThreadEntry, data);
   
        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~Tcp_Server()
    {}
};